var cvs = document.getElementById("cvs");
var ctx = cvs.getContext("2d");

var sc = document.getElementsByClassName("score");
var btns = document.getElementsByTagName("button");

var scores = 0;

btns[0].onclick = function(){
	location.reload();
}

function init(){
	ctx.fillStyle = "rgb(190, 23, 47)";
	ctx.beginPath();
	ctx.arc(50, 485, 15, 0, Math.PI * 2, false);
	ctx.fill();
	
	ctx.fillStyle = "rgb(38, 54, 69)";
	ctx.shadowOffsetX = 5;
	ctx.shadowOffsetY = 5;
	ctx.shadowBlur = 4;
	ctx.shadowColor = "rgba(140, 140, 140, 0.6)"
	ctx.fillRect(0, 500, 80, 100); //x, y, wid, hei
}

function stageGen(){
	var x = 80 + 20 + Math.floor(Math.random()*10*22);
	ctx.fillStyle = "rgb(38, 54, 69)";
	ctx.fillRect(x, 500, 80, 100);
	return x;
}

function start(){
	init();
	res = stageGen();
	console.log(res);
}

function stickDraw(){
	ctx.shadowBlur = 0;
	ctx.shadowOffsetX = 0;
	ctx.shadowOffsetY = 0;
	stickY = 0;
	val = setInterval(function(){
		if (stickY >= 500 ) {
			clearInterval(val);
		}else{
			stickY++;
			ctx.clearRect(70, 500, 50, -500);
			ctx.fillStyle = "rgb(73, 36, 21)";
			ctx.fillRect(70, 500, 10, -stickY);
		}
	},10);
}

function handleMouseDown() {  
    stickDraw();  
    console.log('down' + stickY);  
}  
  
cvs.addEventListener('mousedown', handleMouseDown);  

function rotateBlock(){
	ctx.translate(80, 500);
	ctx.clearRect(0, 0, -10, -500);
	ctx.save();
	ctx.rotate(90 * Math.PI / 180);
	ctx.fillStyle = "rgb(73, 36, 21)";
	ctx.fillRect(0, 0, -10, -stickY);
	ctx.restore();
}

function judgeOver(){
	if(stickY < (res-80) || stickY > res){
		console.log("游戏结束");
		ctx.translate(-80, -500);
		cvs.removeEventListener('mousedown', handleMouseDown);
		ctx.shadowOffsetX = 5;
		ctx.shadowOffsetY = 5;
		ctx.shadowBlur = 4;
		ctx.shadowColor = "rgba(140, 140, 140, 0.6)"
		ctx.fillStyle = "rgb(89, 109, 143)";
		ctx.font = '60px Verdana';
		ctx.textAlign = 'center';
		ctx.fillText("游戏结束", 200, 200);
		cvs.removeEventListener('mouseup', handleMouseUp);
		btns[0].style.display = "inline";
	}else{
		console.log("继续");
		scores++;
		sc[0].innerHTML = scores;
		stickY = 0;
		setTimeout(function(){
			ctx.translate(-80, -500);
			ctx.clearRect(0, 0, 400, 600);
			start();
		},500);
	}  
}

function handleMouseUp() {  
	if (val){
		clearInterval(val);
	}
	rotateBlock();
	console.log('up'+stickY);
	judgeOver();
}

cvs.addEventListener('mouseup', handleMouseUp);



window.onload = function(){
	start();
}

